package com.hanbang.chu_xing_gao_zhao.view_information;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.hanbang.chu_xing_gao_zhao.application.HttpInterfaces;
import com.hanbang.chu_xing_gao_zhao.base.MainActivity;
import com.hanbang.chu_xing_gao_zhao.entity.InformationContentData;
import com.hanbang.chu_xing_gao_zhao.entity.InformationJsonData;
import com.hanbang.chu_xing_gao_zhao.entity.InformationTeitleData;
import com.hanbang.chu_xing_gao_zhao.myview.ListViewForScrollView;
import com.hanbang.chu_xing_gao_zhao.utils.JsonHelper;
import com.hanbang.chu_xing_gao_zhao.utils.MyRequestCallBack;
import com.hanbang.chu_xing_gao_zhao.utils.MySharedPreferences;
import com.hanbang.chu_xing_gao_zhao.utils.MyToast;
import com.hanbang.chu_xing_gao_zhao.utils.StringUtils_2;
import com.hanbang.chu_xing_gao_zhao.utils.SystemTools;
import com.hanbang.chu_xing_gao_zhao.utils.TimeTools;
import com.hanbang.chu_xing_gao_zhao.utils.UiUtils;
import com.hanbang.cxgz_2.R;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class InformationActivity extends MainActivity {
    /**
     * 底部导航按钮
     */
    private LinearLayout information;
    /**
     * listViw 列表
     */
    private PullToRefreshListView listView;
    /**
     * 适配器
     */
    private TitleAdapter listViewAdapter;

    /**
     * 列表数据
     */
    private ArrayList<InformationContentData> listContetnData;

    /**
     * 列表数据
     */
    private ArrayList<InformationTeitleData> listTitleData;

    private int year;
    private int month;
    private int day;

    int index = 0;

    List<InformationJsonData> listHttp = new ArrayList<InformationJsonData>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.information_activity);

        initView();
        getInformaiton(year, month, day);

        setOnClickListener();
        setUpViewsAndAddLinstener(information);
        addListViewAdapter();

    }

    /**
     * 初始化view
     */
    private void initView() {
        information = (LinearLayout) findViewById(R.id.bar_botton_bar_information);
        listView = (PullToRefreshListView) findViewById(R.id.lv_information_activity_listview);
        listContetnData = new ArrayList<InformationContentData>();
        listTitleData = new ArrayList<InformationTeitleData>();

        year = TimeTools.getYear();
        month = TimeTools.getMonth();
        day = TimeTools.getDay();

    }

    /**
     * 处理监听
     */
    private OnClickListener myonClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.tv_bar_top_conver_classify_title2:
//                    MyToast.show(InformationActivity.this, "正在建设中...", 1);
                    setTitleMore(View.GONE, View.GONE, "热点资讯", "招聘求职", null, null);
                    ((TextView) findViewById(R.id.tv_bar_top_conver_classify_title2)).setBackgroundResource(R.color.white);
                    ((TextView) findViewById(R.id.tv_bar_top_conver_classify_title1)).setBackgroundResource(R.color.yellow);
                    ((LinearLayout) findViewById(R.id.ll_information_activity_parent)).setVisibility(View.INVISIBLE);
                    ((TextView) findViewById(R.id.tv_information_activity_hint)).setVisibility(View.VISIBLE);

                    break;

                case R.id.tv_bar_top_conver_classify_title1:
                    setTitleMore(View.GONE, View.GONE, "热点资讯", "招聘求职", null, null);
                    ((TextView) findViewById(R.id.tv_bar_top_conver_classify_title1)).setBackgroundResource(R.color.white);
                    ((TextView) findViewById(R.id.tv_bar_top_conver_classify_title2)).setBackgroundResource(R.color.yellow);
                    ((LinearLayout) findViewById(R.id.ll_information_activity_parent)).setVisibility(View.VISIBLE);
                    ((TextView) findViewById(R.id.tv_information_activity_hint)).setVisibility(View.GONE);

                    break;

                default:
                    break;
            }

        }
    };

    /**
     * 设置点击事件
     */
    private void setOnClickListener() {
        ((TextView) findViewById(R.id.tv_bar_top_conver_classify_title2)).setOnClickListener(myonClickListener);
        ((TextView) findViewById(R.id.tv_bar_top_conver_classify_title1)).setOnClickListener(myonClickListener);

        listView.setMode(Mode.BOTH);
        index = 0;
        // listview 的上下刷新
        listView.setOnRefreshListener(new OnRefreshListener2<ListView>() {

            @Override
            public void onPullDownToRefresh(PullToRefreshBase refreshView) {
                index = 0;
                queryDataBase(year, month, day);

                // 延迟1秒停止刷新
                listView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        listView.onRefreshComplete();
                    }
                }, 1000);

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase refreshView) {

                try {

                    // 没有内容直接返回
                    if (listHttp == null || index == listHttp.size()) {

                        // 延迟1秒停止刷新
                        listView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                listView.onRefreshComplete();
                            }
                        }, 1000);

                        return;
                    } else {

                        listHttp = dbUtils.findAll(Selector.from(InformationJsonData.class)
                                .where("date", "<", listTitleData.get(listTitleData.size() - 1).getDate())
                                .orderBy("date", true));

                        // MyLog.i("text", "*000listHttp.size**" +
                        // listHttp.size());// *****

                        if (listHttp.size() == 0) {

                            // 延迟1秒停止刷新
                            listView.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    listView.onRefreshComplete();
                                }
                            }, 1000);

                            return;
                        }
                    }

                    index = index > listHttp.size() ? listHttp.size() : index;

                    int oldSize = listTitleData.size();
                    // MyLog.i("text", "*111*index*" + index);// *****

                    try {
                        JSONObject json = new JSONObject(listHttp.get(0).getJson());

                        JSONArray tileData = json.getJSONArray("category");

                        JSONArray content = json.getJSONArray("list");

                        // 把数据从接口解析出来
                        listTitleData.addAll(JsonHelper.parseCollection(tileData, ArrayList.class,
                                InformationTeitleData.class));

                        listContetnData.addAll(JsonHelper.parseCollection(content, ArrayList.class,
                                InformationContentData.class));

                        listViewAdapter.notifyDataSetChanged();
                        // MyLog.i("text", "*222*oldSize*" + oldSize);// *****

                        /**
                         * 给标题集合加入日期 1，先记录旧的集合大小，
                         *
                         * 2，遍历新加入标题
                         *
                         */
                        for (int i = 0; i < listTitleData.size() - oldSize; i++) {

                            // MyLog.i("text", "*222*listTitleData.size*" +
                            // listTitleData.size());// *****
                            listTitleData.get(oldSize + i).setDate(listHttp.get(0).getDae());

                        }

                        index++;

                        // 延迟1秒停止刷新
                        listView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                listView.onRefreshComplete();
                            }
                        }, 1000);

                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                } catch (DbException e) {

                    e.printStackTrace();
                }

            }
        });

    }

    /**
     * 查询数据库
     */
    private void queryDataBase(int year, int month, int day) {

        try {
            listTitleData.clear();
            listContetnData.clear();

            listHttp = dbUtils.findAll(Selector.from(InformationJsonData.class).where("date", "<=",
                    year + "-" + month + "-" + day));

            JSONObject json = new JSONObject(listHttp.get(0).getJson());

            JSONArray tileData = json.getJSONArray("category");
            JSONArray content = json.getJSONArray("list");
            // 把数据从接口解析出来
            listTitleData.addAll(JsonHelper.parseCollection(tileData, ArrayList.class, InformationTeitleData.class));

            listTitleData.get(index).setDate(listHttp.get(0).getDae());

            listContetnData.addAll(JsonHelper.parseCollection(content, ArrayList.class, InformationContentData.class));

            listViewAdapter.notifyDataSetChanged();

        } catch (Exception e) {
            e.printStackTrace();
            MyToast.show(InformationActivity.this, "暂无内容", 1);
        }

    }

    /**
     * 为listview 添加adapter
     */
    private void addListViewAdapter() {
        listViewAdapter = new TitleAdapter();
        listView.setAdapter(listViewAdapter);

    }

    /**
     * 为listView 添加临时数据
     */
    public void addData() {
    }

    @Override
    protected void onResume() {
        setTitleMore(View.GONE, View.GONE, "热点资讯", "招聘求职", null, null);
        ((TextView) findViewById(R.id.tv_bar_top_conver_classify_title1)).setBackgroundResource(R.color.white);
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * adapter 设置
     *
     * @author Administrator
     */
    class TitleAdapter extends BaseAdapter {
        public TitleAdapter() {

        }

        @Override
        public int getCount() {
            return listTitleData.size();
        }

        @Override
        public InformationTeitleData getItem(int position) {
            return listTitleData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder viewHolder;
            if (convertView == null) {// 是空加载tiem
                // 指定item视图
                convertView = getLayoutInflater().inflate(R.layout.item_information_hottest, null);
                // 改变字体
                UiUtils.applyFont(convertView);

                viewHolder = new ViewHolder();

                viewHolder.date = (TextView) convertView.findViewById(R.id.item_information_data);
                viewHolder.title = (TextView) convertView.findViewById(R.id.item_information_classify);
                viewHolder.contentListView = (ListViewForScrollView) convertView
                        .findViewById(R.id.lv_item_information_listView);

                convertView.setTag(viewHolder);// 把现有item对象存起来
            } else {// 不是空复用

                viewHolder = (ViewHolder) convertView.getTag();
            }

            // item 的各项数据赋值
            final InformationTeitleData data = getItem(position);

            if (listTitleData.get(position).getDate() != null) {
                viewHolder.date.setVisibility(View.VISIBLE);
                viewHolder.date.setText(listTitleData.get(position).getDate());

                if (listTitleData.size() > 1 && position > 1) {

                    if (listTitleData.get(position).getDate().equals((listTitleData.get(position - 1).getDate()))) {
                        viewHolder.date.setVisibility(View.GONE);
                    }
                }

            } else {
                viewHolder.date.setVisibility(View.GONE);
            }

            viewHolder.title.setText(String.valueOf(data.getTitle()));

            viewHolder.contentListView.setAdapter(new ContentAdapter(data.getId(), listTitleData.get(position)
                    .getDate()));

            /**
             * item 的监听
             */
            viewHolder.contentListView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent = new Intent(InformationActivity.this, InformationDetailsActivity.class);

                    intent.putExtra("position", (int) id);

                    startActivity(intent);

                }
            });

            return convertView;
        }

        class ViewHolder {// 进行缓存保存
            private TextView date;
            private TextView title;

            private ListViewForScrollView contentListView;

        }

    }

    /**
     * adapter 设置
     *
     * @author Administrator
     */
    class ContentAdapter extends BaseAdapter {

        public ArrayList<InformationContentData> list = new ArrayList<InformationContentData>();

        public ContentAdapter(int id, String date) {

            // 添加同天的数据
            for (int i = 0; i < listContetnData.size(); i++) {

                long l = Long.parseLong(StringUtils_2.getNum(listContetnData.get(i).getAdd_time()));

                String data3 = null;
                try {
                    data3 = TimeTools.converLongToString(l, "yyyy-M-d");

                } catch (ParseException e) {
                    e.printStackTrace();
                }

                // 判断类型相同，并且日期相同，放在一起
                if (listContetnData.get(i).getCategory_id() == id && data3.equals(date)) {

                    list.add(listContetnData.get(i));
                }
            }

        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public InformationContentData getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return list.get(position).getId();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder viewHolder;
            if (convertView == null) {// 是空加载tiem
                // 指定item视图
                convertView = getLayoutInflater().inflate(R.layout.item_information_hottest_content, null);
                UiUtils.applyFont(convertView);
                viewHolder = new ViewHolder();

                viewHolder.img_url = (ImageView) convertView.findViewById(R.id.item_information_advertismmentImageId);
                viewHolder.img_url_small = (ImageView) convertView
                        .findViewById(R.id.item_information_portraitImageIdUp);

                viewHolder.zhaiyao = (TextView) convertView.findViewById(R.id.item_information_nameUp);

                convertView.setTag(viewHolder);// 把现有item对象存起来
            } else {// 不是空复用

                viewHolder = (ViewHolder) convertView.getTag();
            }

            // item 的各项数据赋值
            InformationContentData data = getItem(position);

            if ((data.getImg_url() != null)) {

                bitmapUtils.display(viewHolder.img_url_small, SystemTools.getHttpFileUrl(data.getImg_url()));
            } else {
                viewHolder.img_url_small.setImageResource(R.drawable.default_2);
            }

            viewHolder.zhaiyao.setText(data.getTitle());

            if (position == 0) {
                viewHolder.img_url.setVisibility(View.VISIBLE);

                if ((data.getImg_url() != null)) {
                    bitmapUtils.display(viewHolder.img_url, SystemTools.getHttpFileUrl(data.getImg_url()));
                } else {
                    viewHolder.img_url.setImageResource(R.drawable.default_1);
                }

            } else {
                viewHolder.img_url.setVisibility(View.GONE);
            }

            return convertView;
        }

        class ViewHolder {// 进行缓存保存

            private ImageView img_url;
            private ImageView img_url_small;
            private TextView zhaiyao;

        }

    }

    /**
     * 得到信息列表
     */
    private void getInformaiton(final int year, final int month, final int day) {
        List<InformationJsonData> list;

        // 判断今天的信息有没有储存到数据库，有则从数据库中读取
        try {
            list = dbUtils.findAll(Selector.from(InformationJsonData.class).where("date", "=",
                    year + "-" + month + "-" + day));

            if (list != null) {

                if (list.size() > 0) {
                    queryDataBase(year, month, day);

                    return;
                }

            }

        } catch (DbException e1) {

            e1.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(
                InformationActivity.this, MySharedPreferences.USER_DATA, "tlephone"));
        params.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(
                InformationActivity.this, MySharedPreferences.USER_DATA, "password"));

        params.addBodyParameter("year", year + "");
        params.addBodyParameter("month", month + "");
        params.addBodyParameter("day", day + "");

        httpUtils.send(HttpMethod.POST, HttpInterfaces.GetInfo, params,
                new MyRequestCallBack<String>(this, "页面加载中...") {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        super.onSuccess(responseInfo);

                        try {

                            JSONObject json = new JSONObject(responseInfo.result);

                            String result = json.getString("Result");

                            if (result == "true") {

                                // 把讯问到的信息储存到数据库
                                InformationJsonData jsonData = new InformationJsonData();
                                jsonData.setJson(json.toString());
                                jsonData.setDae(year + "-" + month + "-" + day);
                                dbUtils.save(jsonData);

                                queryDataBase(year, month, day);

                            } else {
                                queryDataBase(year, month, day);

                                MyToast.show(InformationActivity.this, "今日暂无内容", 1);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        // 停止刷新
                        listView.onRefreshComplete();
                    }
                });

    }
}
